﻿#if NETFX_CORE
using System.Windows.Input;

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Nx.Commands
{

    /// <remarks>
    /// This behavior is only available on WinRT
    /// </remarks>    
    public static class ItemClick
    {
        private static readonly DependencyProperty ItemClickCommandBehaviorProperty = DependencyProperty.RegisterAttached(
           "ItemClickCommandBehavior",
           typeof(ListViewBaseItemClickBehavior),
           typeof(ItemClick),
           null);

        public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached(
            "Command",
            typeof(ICommand),
            typeof(ItemClick),
            new PropertyMetadata(null, OnSetCommandCallback));

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Only works for buttonbase")]
        public static void SetCommand(UIElement control, ICommand command)
        {
            if (control == null) throw new System.ArgumentNullException("control");
            control.SetValue(CommandProperty, command);
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Only works for buttonbase")]
        public static ICommand GetCommand(UIElement control)
        {
            if (control == null) throw new System.ArgumentNullException("control");
            return control.GetValue(CommandProperty) as ICommand;
        }

        private static void OnSetCommandCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            ListViewBase control = dependencyObject as ListViewBase;
            if (control != null)
            {
                ListViewBaseItemClickBehavior behavior = GetOrCreateBehavior(control);
                behavior.Command = e.NewValue as ICommand;
            }
        }

        private static ListViewBaseItemClickBehavior GetOrCreateBehavior(ListViewBase control)
        {
            ListViewBaseItemClickBehavior behavior = control.GetValue(ItemClickCommandBehaviorProperty) as ListViewBaseItemClickBehavior;
            if (behavior == null)
            {
                behavior = new ListViewBaseItemClickBehavior(control);
                control.SetValue(ItemClickCommandBehaviorProperty, behavior);
            }

            return behavior;
        }
    }
}
#endif